"""
Case Type   : gms_output
Case Name   : 恢复数据库
Create At   : 2024/08/06
Owner       : zbanbiao.chen
Description :
    1、修改参数以支持删除插件
    2、删除插件gms_output,验证成功
    3、恢复参数
    4、删除测试库。
Expect      :
    1、成功
    2、成功
    3、成功
    4、成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class CompatibilityTest02(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.common = Common()
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.user_node = Node('PrimaryDbUser')
        self.constant = Constant()
        
    def test_gms_output(self):

        self.log.info(f'-----{os.path.basename(__file__)} start-----')

        self.log.info('--step1:设置参数值为on,以允许执行删除插件操作,并重启数据库生效--')
        msg = self.sh_primary.execute_gsguc('set',
                                     self.constant.GSGUC_SUCCESS_MSG,
                                     'support_extended_features = on')
        self.log.info(msg)
        msg = self.sh_primary.restart_db_cluster()
        self.log.info(msg)
        status = self.sh_primary.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status)

        text = '--step2:删除插件，查询插件不存在--'
        self.log.info(text)
        sql_cmd = f'''drop extension  gms_output;
                      select extname from pg_extension where extname ='gms_output';
                   '''
        self.log.info(sql_cmd)
        sql_res = self.sh_primary.execut_db_sql(sql_cmd, dbname=self.user_node.db_name)
        self.log.info(sql_res)
        self.assertIn(self.constant.drop_extension_success, sql_res, '执行失败' + text)
        self.assertIn('(0 rows)', sql_res, '执行失败' + text)

        self.log.info('--step3:恢复参数默认值为off并重启数据库--')
        msg = self.sh_primary.execute_gsguc('set',
                                     self.constant.GSGUC_SUCCESS_MSG,
                                     'support_extended_features = off')
        self.log.info(msg)
        msg = self.sh_primary.restart_db_cluster()
        self.log.info(msg)
        status = self.sh_primary.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status)

        text = '--step4:恢复数据库;expect:成功--'
        self.log.info(text)
        sql_cmd = f"drop database {self.user_node.db_name};" \
                  f"create database {self.user_node.db_name};"
        self.log.info(sql_cmd)
        sql_res = self.sh_primary.execut_db_sql(sql_cmd, dbname='postgres')
        self.log.info(sql_res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, sql_res, '执行失败' + text)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_res, '执行失败' + text)

    def tearDown(self):

        self.log.info(f'-----{os.path.basename(__file__)} end-----')
 
